package library.and.xps.com.step.view.activity;

import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jude.utils.JUtils;
import com.lvfq.pickerview.TimePickerView;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.Request;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import library.and.xps.com.step.R;
import library.and.xps.com.step.URLConstants;
import library.and.xps.com.step.m.model.ActiveDetailIntentParams;
import library.and.xps.com.step.m.model.CreateActive;
import library.and.xps.com.step.m.model.CreateActiveParams;
import library.and.xps.com.step.m.model.RequestParams;
import library.and.xps.com.step.m.netapi.OkHttpClientUtils;
import library.and.xps.com.step.net.ResponceWrapper;
import library.and.xps.com.step.util.AppCommond;
import library.and.xps.com.step.util.HttpResponsHelper;
import library.and.xps.com.step.util.RequestCallback;
import library.and.xps.com.step.view.base.BaseActivity;
import library.and.xps.com.step.view.fragment.ActiveFormatFragment;
import library.and.xps.com.step.view.fragment.ActiveInfoSetupFragment;
import library.and.xps.com.step.view.fragment.ActiveTypeSetupFragment;


public class CreateActiveActivity extends BaseActivity {
    ImageView iv_back;
    TextView tv_next;

    ActiveTypeSetupFragment activeMatchTypeFragment;
    ActiveFormatFragment activeFormatFragment;
    ActiveInfoSetupFragment activeInfoSetup;

    FragmentTransaction ft;
    FragmentManager fragmentManager;

    CreateActiveParams createActiveParams;

    @Override
    protected int getLayout() {
        return R.layout.activity_create_active;
    }

    @Override
    protected void setData() {
        fragmentManager = getSupportFragmentManager();

        activeMatchTypeFragment = new ActiveTypeSetupFragment();
        activeFormatFragment = new ActiveFormatFragment();
        activeInfoSetup = new ActiveInfoSetupFragment();

        ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.container, activeMatchTypeFragment, activeMatchTypeFragment.getClass().getSimpleName()).addToBackStack(activeMatchTypeFragment.getClass().getSimpleName());
        ft.show(activeMatchTypeFragment).commit();
    }

    @Override
    protected void init() {
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        iv_back = r2v(R.id.actionbar_iv_back);
        iv_back.setOnClickListener(this);
        createActiveParams = new CreateActiveParams();
        tv_next = r2v(R.id.actionbar_tv_right);
        ((TextView) r2v(R.id.actionbar_tv_title)).setText("创建活动");
        tv_next.setText("下一步");
        tv_next.setVisibility(View.VISIBLE);
        tv_next.setOnClickListener(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveEvent(CreateActiveParams param) {
        if (param != null) {
            if (!TextUtils.isEmpty(param.getTaname())) {
                createActiveParams.setTaname(param.getTaname());
            }
            if (!TextUtils.isEmpty(param.getTeamid())) {
                createActiveParams.setTeamid(param.getTeamid());
            }
            if (!TextUtils.isEmpty(param.getMark())) {
                createActiveParams.setMark(param.getMark());
            }
            if (!TextUtils.isEmpty(param.getType())) {
                createActiveParams.setType(param.getType());
                if (param.getType().equals("GPS室外运动排位赛")) {
                    activeFormatFragment.setGoalEditText("请输入目标公里数");
                    activeFormatFragment.setActiveType(TimePickerView.Type.ALL);
                } else {
                    activeFormatFragment.setGoalEditText("请输入目标步数");
                    activeFormatFragment.setActiveType(TimePickerView.Type.YEAR_MONTH_DAY);
                }
            }
            if (!TextUtils.isEmpty(param.getFormat())) {
                createActiveParams.setFormat(param.getFormat());
            }
            if (!TextUtils.isEmpty(param.getDescribe())) {
                createActiveParams.setDescribe(param.getDescribe());
            }
            if (!TextUtils.isEmpty(param.getEndtime())) {
                createActiveParams.setEndtime(param.getEndtime());
            }
            if (!TextUtils.isEmpty(param.getStarttime())) {
                createActiveParams.setStarttime(param.getStarttime());
            }
            if (!TextUtils.isEmpty(param.getExercise())) {
                createActiveParams.setExercise(param.getExercise());
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            popupStack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    void popupStack() {
        if (!activeMatchTypeFragment.isVisible()) {
            fragmentManager.popBackStackImmediate();
            tv_next.setText("下一步");
        } else finish();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.actionbar_tv_right:

                if (activeInfoSetup.isVisible() && activeInfoSetup.next()) {
                    //todo 请求创建活动
                    doCreateTeamActivity();
                } else {
                    nextClick();
                }

                break;
            case R.id.actionbar_iv_back:
                popupStack();
                break;
        }
    }

    //创建团队活动
    void doCreateTeamActivity() {
        JSONObject json = produceJson();
        OkHttpClientUtils.postJsonStringAsync(this, URLConstants.TEAMACTIVE.ADDACTIVITY, json.toString(), new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                e.printStackTrace();
                dissmisDialog();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();
                if (HttpResponsHelper.SuccessResponce(response)) {
                    Logger.json(response.getBody());

                    CreateActive createActive = new Gson().fromJson(response.getBody(), CreateActive.class);
                    Intent i = new Intent(CreateActiveActivity.this, TeamActiveDetailActivity.class);
                    ActiveDetailIntentParams activeDetailIntentParams = new ActiveDetailIntentParams();
                    activeDetailIntentParams.setDescribe(createActive.getObj().getDescribe());
                    activeDetailIntentParams.setEndtime(createActive.getObj().getEndtime());
                    activeDetailIntentParams.setStarttime(createActive.getObj().getStarttime());
                    activeDetailIntentParams.setActivityid(createActive.getObj().getActivityid());
                    activeDetailIntentParams.setMark(createActive.getObj().getMark());
                    activeDetailIntentParams.setPeople(createActive.getObj().getPeople());
                    activeDetailIntentParams.setType(createActive.getObj().getType());
                    activeDetailIntentParams.setFormat(createActive.getObj().getFormat());
                    activeDetailIntentParams.setTeamid(createActive.getObj().getTeamid());
                    activeDetailIntentParams.setTaname(createActive.getObj().getTaname());
                    i.putExtra("active", activeDetailIntentParams);

                    //// TODO: 2017/5/24  无效?
//                    AppCommond appCommond = new AppCommond.Builder()
//                            .setOpration(AppCommond.CLOSE_ACTIVITY)
//                            .setRequestcloseAcname("TeamActiveActivity")
//                            .build();
//
//                    EventBus.getDefault().post(appCommond);

                    startActivity(i);

                    finish();
                }
            }

            @Override
            public void onStart() {
                showDialog();
            }
        }, "");
    }

    JSONObject produceJson() {
        JSONObject json = RequestParams.getNewInstance().setTaname(createActiveParams.getTaname())
                .setTeamid(createActiveParams.getTeamid())
                .setMark(createActiveParams.getMark())
                .setType(createActiveParams.getType())
                .setFormat(createActiveParams.getFormat())
                .setDescribe(createActiveParams.getDescribe())
                .setEndtime(createActiveParams.getEndtime())
                .setStarttime(createActiveParams.getStarttime())
                .setExercise(createActiveParams.getExercise()).getJson();
        return json;
    }

    void nextClick() {
        if (activeMatchTypeFragment.isVisible() && activeMatchTypeFragment.next()) {
            fragmentManager.beginTransaction()
                    .hide(activeMatchTypeFragment)
                    .add(R.id.container, activeFormatFragment, activeFormatFragment.getClass().getSimpleName())
                    .addToBackStack(activeFormatFragment.getClass().getSimpleName())
                    .show(activeFormatFragment).commit();

        } else if (activeFormatFragment.isVisible() && activeFormatFragment.next()) {
            fragmentManager.beginTransaction()
                    .hide(activeFormatFragment)
                    .add(R.id.container, activeInfoSetup, activeInfoSetup.getClass().getSimpleName())
                    .addToBackStack(activeInfoSetup.getClass().getSimpleName())
                    .show(activeInfoSetup).commit();

            tv_next.setText("创建活动");
        }
    }
}
